<?php

class WorkflowService extends BaseService {

	public function getWorkflowNodes($workflowId) {
		$nodes = WorkflowNode::model()->findAllByAttributes(array('workflow_id' => $workflowId));
		return $this->toArray($nodes);
	}
	
	public function getActivity($activityName) {
		$model = Activity::model()->findByAttributes(array('activity_name' => $activityName));
		return $this->toArray($model);
	}	
	
	public function getWorkflows() {
		$db = Task::model()->dbConnection;
        $command = $db->createCommand('select * from (select * from workflow order by workflow_id DESC, workflow_version DESC) t group by workflow_name');
        $workflows = $command->queryAll();
        return $this->toArray($workflows);
	}
	
	public function getWorkflowByName($name) {
		$db = Task::model()->dbConnection;
        $command = $db->createCommand('select * from (select * from workflow order by workflow_id DESC, workflow_version DESC) t group by workflow_name having workflow_name=\''.$name.'\'');
        $workflows = $command->queryAll();
        return $this->toArray($workflows);
	}
	
	public function deleteByName($name) {
		$workflows = Workflow::model()->findAllByAttributes(array('workflow_name'=>$name));
		foreach ($workflows as $workflow) {
			$this->deleteById($workflow['workflow_id']);
		}
		return true;
	}
	
	public function deleteById($id) {
		Workflow::model()->deleteByPk($id);
		WorkflowNode::model()->deleteAllByAttributes(array(
			'workflow_id'	=>	'$id',
		));
		
		VariableHandler::model()->deleteAllByAttributes(array(
			'workflow_id'	=>	'$id',
		));
	}
}
